package cn.jhc.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet("/accept.do")
public class AcceptServlet extends HttpServlet {
    private static final String CONNECTION_URL = "jdbc:mysql://localhost/questions?user=quser&password=123456&serverTimezone=GMT";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        String subject = req.getParameter("subject");
        String message = req.getParameter("message");
        boolean agree = req.getParameter("agree").equals("true");

        String sql = "insert into question(name, username, email, subject, message, agree) "
                + "values('" + name + "', '" + username + "','" + email + "','" + subject + "','" + message + "', " + agree + ")";
        try(Connection connection = DriverManager.getConnection(CONNECTION_URL)) {
            Statement statement = connection.createStatement();
            statement.execute(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            resp.getWriter().println("{\"ok\": false}");
            return;
        }
        resp.getWriter().println("{\"ok\": true}");
    }
}
